
package com.zhu.salesmanagement.views;

import java.util.ArrayList;

import com.dms2.salesmanagement.R;
import com.zhu.salesmanagement.DealerTaskListActivity;
import com.zhu.salesmanagement.InputMessageActivity;
import com.zhu.salesmanagement.MainActivity;
import com.zhu.salesmanagement.StoreEvaluationActivity;
import com.zhu.salesmanagement.adapters.ProductInfoListAdapter;
import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.models.GoodsType;
import com.zhu.salesmanagement.models.ProductInfo;
import com.zhu.salesmanagement.models.VisitTaskInfo;
import com.zhu.salesmanagement.network.DownloadService;
import com.zhu.salesmanagement.provider.SalesSettings;
import com.zhu.salesmanagement.utils.Util;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

/**
 * 产品考核信息界面
 */
public class ProductInfoListView extends FrameLayout implements View.OnClickListener {

    private final static int P_LIST_QUERY_TOKEN = 998;
    private final static int CP_LIST_QUERY_TOKEN = 999;
    private final static int CPNAME_LIST_QUERY_TOKEN = 997;
    private final static int GOODS_LIST_QUERY_TOKEN = 1000;
    private final static int GOODS_LIST_DELETE_TOKEN = 2000;
    public final static int INVALID_VALUE = -100;
    private final static int TYPE_FLOOR = 100;
    private final static int TYPE_SIDE = 101;
    private final static String TAG = "zhu";
    public final static String SPLIT_ROW = ";";
    public final static String SPLIT_RANK = "&";
    public final static String DEFAULT = "default";
    public final static String MAIN_PC = "YP";

    private Spinner mSpinner = null;
    private EditText mPlaceText = null;
    private EditText mFloorText = null;
    private EditText mSideText = null;
    private Button mTypeText = null;
    private boolean isFirst = true;
    private ArrayList<GoodsType> mGoodsTypeList = new ArrayList<GoodsType>();
    private ScrollView mScrollView = null;
    private LinearLayout mBodyView = null;
    private ArrayList<ProductInfo> lists = new ArrayList<ProductInfo>();
    private TextView mInfoTextView = null;
    private GoodsListQueryHandler mGoodsListQueryHandler = null;
    private int mCurrentTypeIndex = 0;
    private int mLastTypeIndex = 0;
    private String mGoodsId = "0";

    private int mGoodsFloor = INVALID_VALUE;
    private int mGoodsSide = INVALID_VALUE;
    private int mGoodsPlace = INVALID_VALUE;
    private int mGoodsType = INVALID_VALUE;
    private long mDBId = INVALID_VALUE;
    private StoreEvaluationActivity mProductInfoListActivity = null;
    private VisitTaskInfo mVisitTaskInfo = null;
    private int mDefaultFloor = 0;
    private View mRemindView = null;
    private String[] mBijinpingArray = null;
    private String[] mBijinpingValueArray = null;
    private String[] mTechenArray = null;
    private String[] mTechenValueArray = null;
    private String[] mFloorValue = null;
    private String[] mFloorType = null;
    private String[] mStoreType = null;
    private boolean isInited = false;

    public ProductInfoListView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    public ProductInfoListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onFinishInflate() {
        setupViews();
        super.onFinishInflate();
    }

    /**
     * 初始化界面
     */
    private void setupViews() {
        mScrollView = (ScrollView) findViewById(R.id.productinfolist_scrollview);
        mSpinner = (Spinner) findViewById(R.id.productSpinner);
        mInfoTextView = (TextView) findViewById(R.id.infoTextView);
        mBodyView = (LinearLayout) findViewById(R.id.productinfolistview_bodyView);
        mPlaceText = (EditText) findViewById(R.id.productinfo_seat);
        mFloorText = (EditText) findViewById(R.id.productinfo_floor);
        mTypeText = (Button) findViewById(R.id.productinfo_type);
        mTypeText.setOnClickListener(this);
        //mFloorText.setOnClickListener(this);
        //mFloorText.addTextChangedListener(mTextFloorInfoEditorWatcher);
        mSideText = (EditText) findViewById(R.id.productinfo_side);
    }

    /**
     * 重置数据
     */
    private void reset() {
        mDBId = INVALID_VALUE;
        mGoodsFloor = INVALID_VALUE;
        mGoodsSide = INVALID_VALUE;
        mGoodsPlace = INVALID_VALUE;
        mGoodsType = INVALID_VALUE;

        startProductListAsyncQuery(mGoodsTypeList.get(mCurrentTypeIndex).typeId);
        //initListData();
        //startGoodsListAsyncQuery(mGoodsId, mGoodsTypeList.get(mCurrentTypeIndex).typeId);
    }

    /**
     * 初始化数据
     * @param visitTaskInfo 门店信息
     * @param productInfoListActivity  Activity
     */
    public void initData(VisitTaskInfo visitTaskInfo,
            StoreEvaluationActivity productInfoListActivity) {
        if(isInited){
            return;
        }
        isInited = false;
        mTechenArray = this.getContext().getResources().getStringArray(R.array.techen_type);
        mTechenValueArray = this.getContext().getResources().getStringArray(R.array.techen_value);
        mBijinpingArray = this.getContext().getResources().getStringArray(R.array.compare_type);
        mBijinpingValueArray = this.getContext().getResources().getStringArray(R.array.compare_value);
        mFloorType = this.getContext().getResources().getStringArray(R.array.floor_type);
        mFloorValue = this.getContext().getResources().getStringArray(R.array.floor_value);
        mStoreType = this.getContext().getResources().getStringArray(R.array.productinfo_type);

        mVisitTaskInfo = visitTaskInfo;
        mProductInfoListActivity = productInfoListActivity;
        if (Actions.DEBUG) {
            Log.e("zhu", "GoodsId=" + mVisitTaskInfo.id);
        }
        mGoodsId = mVisitTaskInfo.id;
        mGoodsListQueryHandler = new GoodsListQueryHandler(getContext().getContentResolver());
        popRemindDialog(getRemindText(mGoodsId));
        startCPsListAsyncQuery(mGoodsId);
    }

    /**
     * 获取产品大类货架信息
     * @param goodsId 门店id
     */
    private void startCPsListAsyncQuery(String goodsId){
        try {
            mGoodsListQueryHandler.startQuery(CP_LIST_QUERY_TOKEN, null,
                    SalesSettings.ProductShelfsColumns.CONTENT_URI,
                    null, SalesSettings.ProductShelfsColumns.CUSTOMER_ID + "=\"" + goodsId +"\"", null, null);
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取大类产品数据列表
     * @param cpid 大类id
     */
    private void startProductListAsyncQuery(String cpid){
        try {
            mGoodsListQueryHandler.startQuery(P_LIST_QUERY_TOKEN, null,
                    SalesSettings.ProductsColumns.CONTENT_URI,
                    null, SalesSettings.ProductsColumns.PRODUCTCATEGORY_ID + " = \"" + cpid +"\"", null, SalesSettings.ProductsColumns.PRODUCT_SORT + " ASC");
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取大类名字
     * @param where 查询条件
     */
    private void startCPNameListAsyncQuery(String where){
        try {
            mGoodsListQueryHandler.startQuery(CPNAME_LIST_QUERY_TOKEN, null,
                    SalesSettings.ProductCategoryColumns.CONTENT_URI,
                    null, where, null, null);
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新数据库主键ID
     * @param id id
     */
    public void updateDbId(long id){
        mDBId = id;
    }

    /**
     * 初始化大类选择栏
     */
    private void initSpinner() {
        String[] name = new String[mGoodsTypeList.size()];
        for (int i = 0; i < name.length; i++) {
            name[i] = mGoodsTypeList.get(i).typeName;
        }
        ArrayAdapter adapter = new ArrayAdapter<String>(this.getContext(),
                android.R.layout.simple_spinner_item, name);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSpinner.setAdapter(adapter);
        mSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stub
                TextView tv = (TextView)arg1;
                tv.setTextColor(getResources().getColor(R.color.white));
                mLastTypeIndex = mCurrentTypeIndex;
                mCurrentTypeIndex = arg2;
                if (!isFirst) {
                    saveCurrentGoodsInfo(mLastTypeIndex);
                    reset();
                } else {
                    isFirst = false;
                    mLastTypeIndex = mCurrentTypeIndex;
                }
                // saveCurrentGoodsInfo();
                // reset();
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }
        });
    }

    /**
     * 更新大类列表
     * @param cursor 数据库数据
     */
    private void intiGoodsTypeList(Cursor cursor) {
        if (mGoodsTypeList != null) {
            mGoodsTypeList.clear();
        }
        String where = "";
        try {
            final int pcIdIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductShelfsColumns.PRODUCTCATEGORY_ID);
            final int scountIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductShelfsColumns.PRODUCTSHELF_COUNT);
            final int slayerIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductShelfsColumns.PRODUCTSHELF_LAYER);
            final int sareaIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductShelfsColumns.PRODUCTSHELF_AREA);

            while (cursor.moveToNext()) {
                GoodsType item = new GoodsType();
                item.typeId = cursor.getString(pcIdIndex);
                item.sArea = cursor.getString(sareaIndex);
                item.sLayer = cursor.getString(slayerIndex);
                item.sCount = cursor.getString(scountIndex);
                if(item.typeId.equals(MAIN_PC)){
                    mGoodsTypeList.add(0, item);
                }else{
                    mGoodsTypeList.add(item);
                }
                if(where.length() == 0){
                    where = SalesSettings.ProductCategoryColumns.PRODUCTCATEGORY_ID +" = \"" + item.typeId + "\"";
                }else{
                    where += " or " + SalesSettings.ProductCategoryColumns.PRODUCTCATEGORY_ID +" = \"" + item.typeId + "\"";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "intiGoodsTypeList error");
        } finally {
        	if(cursor != null){
        		cursor.close();
        		cursor = null;
        	}
        }

        if(mGoodsTypeList.size() > 0){
            startCPNameListAsyncQuery(where);
            startProductListAsyncQuery(mGoodsTypeList.get(mCurrentTypeIndex).typeId);
        }
    }

    /**
     * 更新大类名字
     * @param cursor 数据库数据
     */
    private void intiGoodsTypeNameList(Cursor cursor){
        try {
            final int pcIdIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductCategoryColumns.PRODUCTCATEGORY_ID);
            final int pcNameIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductCategoryColumns.PRODUCTCATEGORY_NAME);

            while (cursor.moveToNext()) {
                GoodsType item = getGoodsType(cursor.getString(pcIdIndex));
                item.typeName = cursor.getString(pcNameIndex);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "intiGoodsTypeNameList error");
        } finally {
        	if(cursor != null){
        		cursor.close();
        		cursor = null;
        	}
        }
        initSpinner();
    }

    private GoodsType getGoodsType(String typeid){
        for(int i =0; i < mGoodsTypeList.size(); i++){
            GoodsType type = mGoodsTypeList.get(i);
            if(type.typeId.equals(typeid)){
                return type;
            }
        }
        return null;
    }

    /**
     * 更新产品列表
     * @param cursor 数据库数据
     */
    private void initProductListData(Cursor cursor) {
        lists.clear();

        try {
            final int pcIdIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductsColumns.PRODUCTCATEGORY_ID);
            final int pidIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductsColumns.PRODUCT_ID);
            final int pnameIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductsColumns.PRODUCT_NAME);

            while (cursor.moveToNext()) {
                ProductInfo info = new ProductInfo();
                info.id = cursor.getString(pidIndex);
                info.mName = cursor.getString(pnameIndex);
                lists.add(info);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "initProductListData error");
        } finally {
        	if(cursor != null){
        		cursor.close();
        		cursor = null;
        	}
        }
        //if(lists.size() > 0){
            startGoodsListAsyncQuery(mGoodsId, mGoodsTypeList.get(mCurrentTypeIndex).typeId);
        //}else{
            updateBodyView();
            //updateProductInfoView(mGoodsTypeList.get(mCurrentTypeIndex).typeName, mGoodsPlace, mGoodsFloor, mGoodsSide);
        //}
    }

    /**
     * 更新CRC数据
     * @param cursor 数据库数据
     */
    private void updateListData(Cursor cursor) {
        try {
            final int idIndex = cursor.getColumnIndexOrThrow(SalesSettings.StoreCheckInfoColumns._ID);
            final int placeIndex = cursor
                    .getColumnIndexOrThrow(SalesSettings.StoreCheckInfoColumns.PLACE);
            final int floorIndex = cursor
                    .getColumnIndexOrThrow(SalesSettings.StoreCheckInfoColumns.FLOOR);
            final int sideIndex = cursor.getColumnIndexOrThrow(SalesSettings.StoreCheckInfoColumns.SIDE);
            final int goodsIndex = cursor
                    .getColumnIndexOrThrow(SalesSettings.StoreCheckInfoColumns.GOODS);
            final int typeIndex = cursor
            .getColumnIndexOrThrow(SalesSettings.StoreCheckInfoColumns.TYPE);

            while (cursor.moveToNext()) {
                mDBId = cursor.getLong(idIndex);
                if(lists.size() > 0){
                    String goods = cursor.getString(goodsIndex);
                    parseGoods(goods);
                }
                mGoodsFloor = cursor.getInt(floorIndex);
                mGoodsSide = cursor.getInt(sideIndex);
                mGoodsPlace = cursor.getInt(placeIndex);
                mGoodsType = cursor.getInt(typeIndex);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "updateListData error");
        } finally {
        	if(cursor != null){
        		cursor.close();
        		cursor = null;
        	}
        }

        updateProductInfoView(mGoodsTypeList.get(0).typeName, mGoodsPlace, mGoodsFloor, mGoodsSide, mGoodsType);
        updateBodyView();
    }

    /**
     * 更新产品列表界面
     * @param cursor 数据库数据
     */
    private void updateBodyView() {
        if (mBodyView != null) {
            mBodyView.removeAllViews();
        }
        for (int i = 0; i < lists.size(); i++) {
            ProductInfo info = lists.get(i);
            View v = getView(info, i);
            mBodyView.addView(v);
        }
    }

    /**
     * 获取产品列表项界面
     * @param info 产品数据
     * @param index 索引
     */
    private View getView(ProductInfo info, int index) {
        View view = LayoutInflater.from(this.getContext()).inflate(R.layout.productinfolist_item,
                null);
        view.setTag(info);
        view.setBackgroundColor(Color.WHITE);
        updateViews(view, index, info, false);
        return view;
    }

    /**
     * 更新产品列表项界面
     * @param view 列表项界面
     * @param info 产品数据
     * @param index 索引
     * @param isSetListener 是否设置监听
     */
    private void updateViews(View view, int index, ProductInfo info, boolean isSetListener) {
        TextView textView1 = (TextView) view.findViewById(R.id.text1);
        Button textView2 = (Button) view.findViewById(R.id.text2);
        textView2.setOnClickListener(this);
        textView2.setTag(info);
        EditText textView3 = (EditText) view.findViewById(R.id.text3);
        //textView3.addTextChangedListener(mTextSideEditorWatcher);
        //textView3.setOnClickListener(this);
        //textView3.setTag(info);
        Button textView4 = (Button) view.findViewById(R.id.text4);
        textView4.setOnClickListener(this);
        textView4.setTag(info);
        Button textView5 = (Button) view.findViewById(R.id.text5);
        textView5.setOnClickListener(this);
        textView5.setTag(info);
        EditText textView6 = (EditText) view.findViewById(R.id.text6);
        textView1.setText(info.mName);
        textView2.setText(info.mFloor);
        textView3.setText(info.mSide);
        textView4.setText(getSelectCompareString(info.mCompare));
        textView5.setText(getSelectString(info.mTeChen));
        textView6.setText(info.mPrice);

    }

    /**
     * 解析产品数据
     */
    private void parseGoods(String goods) {
        if (Actions.DEBUG) {
            Log.e("zhu", "goods=" + goods);
        }
        if(goods == null || goods.trim().length() == 0){
            if (Actions.DEBUG) {
                Log.e("zhu", "not have product");
            }
            return;
        }
        String[] rowGoods = goods.split(SPLIT_ROW);
        for (int i = 0; i < rowGoods.length; i++) {
            if (Actions.DEBUG) {
                Log.e("zhu", "xx=" + rowGoods[i]);
            }
            String[] rankGoods = rowGoods[i].split(SPLIT_RANK);
            ProductInfo temInfo = getProductInfo(rankGoods[0]);
            if (rankGoods[1].equals(DEFAULT)) {
                rankGoods[1] = "";
            }
            if (rankGoods[2].equals(DEFAULT)) {
                rankGoods[2] = "";
            }
            if (rankGoods[3].equals(DEFAULT)) {
                rankGoods[3] = "";
            }
            if (rankGoods[4].equals(DEFAULT)) {
                rankGoods[4] = "";
            }
            if (rankGoods[5].equals(DEFAULT)) {
                rankGoods[5] = "";
            }
            temInfo.mFloor = rankGoods[1];
            temInfo.mSide = rankGoods[2];
            temInfo.mCompare = rankGoods[3];
            temInfo.mTeChen = rankGoods[4];
            temInfo.mPrice = rankGoods[5];
        }
    }

    private ProductInfo getProductInfo(String id) {
        for (int i = 0; i < lists.size(); i++) {
            if (lists.get(i).id.equals(id)) {
                return lists.get(i);
            }
        }
        return null;
    }

    /**
     * 更新货架信息界面
     * @param seat 坐
     * @param floor 层
     * @param side 面
     * @param type 位置
     */
    private void updateProductInfoView(String name, int seat, int floor, int side, int type) {
        if (mInfoTextView != null) {
            mInfoTextView.setText(getResources().getString(R.string.productinfo));
        }
        if (seat != INVALID_VALUE) {
            mPlaceText.setText(String.valueOf(seat));
        } else {
//            String sCount = mGoodsTypeList.get(mCurrentTypeIndex).sCount;
//            if(sCount != null && sCount.length() > 0){
//                mPlaceText.setText(sCount);
//            }else{
                mPlaceText.setText("");
//            }
        }
        if (side != INVALID_VALUE) {
            mSideText.setText(String.valueOf(side));
        } else {
//            String area = mGoodsTypeList.get(mCurrentTypeIndex).sArea;
//            if(area != null && area.length() > 0){
//                mSideText.setText(area);
//            }else{
//                mSideText.setText(String.valueOf(getContext().getResources().getInteger(R.integer.config_defaultside)));
//            }
                mSideText.setText("");
        }
        if (floor != INVALID_VALUE) {
            mFloorText.setText(getFloorText(floor));
            //mDefaultFloor = floor;
        } else {
//            String layer = mGoodsTypeList.get(mCurrentTypeIndex).sLayer;
//            if(layer != null && layer.length() > 0){
//                mFloorText.setText(layer);
//                //mDefaultFloor = Integer.valueOf(layer);
//            }else{
//                mFloorText.setText(String.valueOf(getContext().getResources().getInteger(R.integer.config_defaultfloor)));
//                //mDefaultFloor = configfloor;
//            }
            mFloorText.setText("");
        }
        if(type != INVALID_VALUE){
            mTypeText.setText(getTypeText(type));
        }else{
            mGoodsType = 2;
            mTypeText.setText(getTypeText(mGoodsType));
            //mTypeText.setText("");
        }
    }

    /**
     * 获取CRC信息
     */
    private void startGoodsListAsyncQuery(String storeid, String typeid) {
        try {
            String where = SalesSettings.StoreCheckInfoColumns.STOREID + "=\'"+ storeid + "\' and "+ 
            SalesSettings.StoreCheckInfoColumns.TYPEID +"=\'" + typeid +"\' and " + 
            SalesSettings.StoreCheckInfoColumns.DATATYPE +"=1";
            mGoodsListQueryHandler.startQuery(GOODS_LIST_QUERY_TOKEN, null,
                    SalesSettings.StoreCheckInfoColumns.CONTENT_URI,
                    null, where, null, null);
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
    }

    private final class GoodsListQueryHandler extends AsyncQueryHandler {
        public GoodsListQueryHandler(ContentResolver contentResolver) {
            super(contentResolver);
        }

        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            switch (token) {
                case CP_LIST_QUERY_TOKEN:
                    intiGoodsTypeList(cursor);
                    break;
                case CPNAME_LIST_QUERY_TOKEN:
                    intiGoodsTypeNameList(cursor);
                    break;
                case P_LIST_QUERY_TOKEN:
                    initProductListData(cursor);
                    break;
                case GOODS_LIST_QUERY_TOKEN:
                    updateListData(cursor);
                    break;
                default:
                    Log.e(TAG, "onQueryComplete called with unknown token " + token);
            }
        }

        @Override
        protected void onDeleteComplete(int token, Object cookie, int result) {
            switch (token) {
                case GOODS_LIST_DELETE_TOKEN:
                    break;
                default:
                    Log.e(TAG, "onDeleteComplete called with unknown token " + token);
            }
        }
    }

    /**
     * 保存当前大类CRC数据
     * @param index 大类索引
     */
    private boolean saveCurrentGoodsInfo(int index) {
        if(mGoodsType == INVALID_VALUE){
            Actions.toastShort(getContext(), getContext().getString(R.string.savefail_needtype));
            return false;
        }
        String placetext = mPlaceText.getText().toString().trim();
        if (placetext == null || placetext.length() < 1) {
            mGoodsPlace = INVALID_VALUE;
        } else {
            mGoodsPlace = Integer.valueOf(placetext);
        }

        String sidetext = mSideText.getText().toString().trim();
        if (sidetext == null || sidetext.length() < 1) {
            mGoodsSide = INVALID_VALUE;
        } else {
            mGoodsSide = Integer.valueOf(sidetext);
        }

        String floortext = mFloorText.getText().toString().trim();
        if (floortext == null || floortext.length() < 1) {
            mGoodsFloor = INVALID_VALUE;
        } else {
            mGoodsFloor = Integer.valueOf(floortext);
        }

        ContentValues values = new ContentValues();
        ContentResolver cr = this.getContext().getContentResolver();
        values.put(SalesSettings.StoreCheckInfoColumns.STOREID, mGoodsId);
        values.put(SalesSettings.StoreCheckInfoColumns.TYPEID, mGoodsTypeList.get(index).typeId);
        values.put(SalesSettings.StoreCheckInfoColumns.PLACE, mGoodsPlace);
        values.put(SalesSettings.StoreCheckInfoColumns.SIDE, mGoodsSide);
        values.put(SalesSettings.StoreCheckInfoColumns.FLOOR, mGoodsFloor);
        values.put(SalesSettings.StoreCheckInfoColumns.TYPE, mGoodsType);
        values.put(SalesSettings.StoreCheckInfoColumns.DATATYPE, 1);
        values.put(SalesSettings.StoreCheckInfoColumns.GOODS, getGoods());
        if (mDBId == INVALID_VALUE) {
            values.put(SalesSettings.StoreCheckInfoColumns.DTASKACTUALID, mVisitTaskInfo.mDatingTaskActualID/*Util.getDatingTaskActualID(Util.mVerifyUserResult.id, mGoodsId)*/);
            cr.insert(SalesSettings.StoreCheckInfoColumns.CONTENT_URI, values);
        } else {
            values.put(SalesSettings.StoreCheckInfoColumns._ID, mDBId);
            cr.update(SalesSettings.StoreCheckInfoColumns.getContentUri(mDBId, false), values, null,
                    null);
        }
        return true;
    }

    /**
     * 保存数据
     * @param isFinish 是否退出界面
     */
    public void saveData(boolean isFinish) {
        try{
            if(saveCurrentGoodsInfo(mCurrentTypeIndex)){
                Actions.toastShort(getContext(), getContext().getString(R.string.save_success));
                if(isFinish){
                    mProductInfoListActivity.finish();
                }
            }
        }catch(Exception e){
            Actions.toastShort(getContext(), getContext().getString(R.string.save_failed));
        }
    }

    /**
     * 获取产品数据
     */
    private String getGoods() {
        String content = "";
        ProductInfo temInfo = null;
        View view = null;
        for (int i = 0; i < mBodyView.getChildCount(); i++) {
            view = mBodyView.getChildAt(i);
            temInfo = (ProductInfo) view.getTag();
            if (temInfo.id == null) {
                continue;
            }
            updateProductInfoFormView(temInfo, view);
            if (temInfo.mFloor == null || temInfo.mFloor.trim().length() < 1) {
                temInfo.mFloor = DEFAULT;
            }
            if (temInfo.mSide == null || temInfo.mSide.trim().length() < 1) {
                temInfo.mSide = DEFAULT;
            }
            if (temInfo.mStock == null || temInfo.mStock.trim().length() < 1) {
                temInfo.mStock = DEFAULT;
            }
            if (temInfo.mPrice == null || temInfo.mPrice.trim().length() < 1) {
                temInfo.mPrice = DEFAULT;
            }
            if (temInfo.mTeChen == null || temInfo.mTeChen.trim().length() < 1) {
                temInfo.mTeChen = DEFAULT;
            }
            if (temInfo.mCompare == null || temInfo.mCompare.trim().length() < 1) {
                temInfo.mCompare = DEFAULT;
            }
            String row = temInfo.id + SPLIT_RANK + temInfo.mFloor + SPLIT_RANK +
                    temInfo.mSide + SPLIT_RANK + temInfo.mCompare + SPLIT_RANK + temInfo.mTeChen + SPLIT_RANK + temInfo.mPrice;
            content += (row + SPLIT_ROW);
        }
        return content;
    }

    /**
     * 更新产品列表项数据
     * @param view 列表项界面
     * @param info 产品信息
     */
    private void updateProductInfoFormView(ProductInfo info, View view) {
        Button textView2 = (Button) view.findViewById(R.id.text2);
        info.mFloor = textView2.getText().toString().trim();
        EditText textView3 = (EditText) view.findViewById(R.id.text3);
        info.mSide = textView3.getText().toString().trim();
        EditText textView6 = (EditText) view.findViewById(R.id.text6);
        info.mPrice = textView6.getText().toString().trim();
    }

    private void showSaveDialog() {
        Dialog alertDialog = new AlertDialog.Builder(this.getContext())
                .setTitle(R.string.save_title)
                .setMessage(R.string.save_content)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setPositiveButton(R.string.queding, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                    }
                }).create();
        alertDialog.show();
    }

    /*
     * (non-Javadoc)
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v != null) {
            switch (v.getId()) {
                case R.id.text3:
                    popDialog((Button)v, TYPE_SIDE);
                    break;
                case R.id.text2:
                    popDialog((Button)v, TYPE_FLOOR);
                    break;
                case R.id.text5:
                    popSelectPosDialog((Button)v);
                    break;
                case R.id.text4:
                    popSelectCompareDialog((Button)v);
                    break;
                case R.id.productinfo_floor:
                	popSeleteFloorDialog((Button)v);
                	break;
                case R.id.productinfo_type:
                    popSeleteTypeDialog((Button)v);
                    break;
            }
        }
    }

    /**
     * 选择层OR面对话框
     * @param button 层OR面View
     * @param type 类型
     */
    private void popDialog(final Button button, int type){
        int maxCount = 0;
        int titleid = 0;

        if(type == TYPE_SIDE){
            titleid = R.string.selectside;
            String side = mSideText.getText().toString().trim();
            if(side != null && side.length() > 0){
                maxCount = Integer.parseInt(side);
            }
        }else{
            titleid = R.string.selectfloor;
            String floor =mFloorText.getText().toString().trim(); // getFloorValue(mGoodsFloor);
            if(floor != null && floor.length() > 0){
                maxCount = Integer.parseInt(floor);
            }
        }
        if(maxCount == 0){
            Actions.toastShort(getContext(), getContext().getString(R.string.writestoreinfo));
            return;
        }

        int selectedItem = 0;

        String curFloor = button.getText().toString();
        if(curFloor == null || curFloor.length() < 1){
        	selectedItem = 0;
        }else{
        	selectedItem = Integer.valueOf(button.getText().toString());
        }

        final String[] dataArray = new String[maxCount + 1];
        for(int i = 1; i < dataArray.length + 1; i++){
        	if(i == 1){
        		dataArray[i-1] = getContext().getString(R.string.defaultfloor);
        	}else{
        		dataArray[i-1] = String.valueOf(i - 1);
        	}
        }
        new AlertDialog.Builder(getContext())
        .setTitle(titleid)
        .setSingleChoiceItems(dataArray, selectedItem,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int which) {
                    	if(which == 0 ){
                    		button.setText("");
                    	}else{
                    		button.setText(dataArray[which]);
                    	}
                    	dialog.dismiss();
                    }
                }).show();
    }

    /**
     * 选择层特陈对话框
     * @param button 特陈View
     */
    private void popSelectPosDialog(final Button button){
        final ProductInfo info = (ProductInfo)button.getTag();
        int selectedItem = getSelecledTechen(info.mTeChen);

        new AlertDialog.Builder(getContext())
        .setTitle(R.string.selectliechen)
        .setSingleChoiceItems(mTechenArray, selectedItem,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int which) {
                        if(which == 0){
                            button.setText("");
                        }else{
                            button.setText(mTechenArray[which]);
                        }
                        dialog.dismiss();
                        info.mTeChen = mTechenValueArray[which];
                    }
                }).show();
    }

    /**
     * 选择比竞品对话框
     * @param button 比竞品View
     */
    private void popSelectCompareDialog(final Button button){
        final ProductInfo info = (ProductInfo)button.getTag();
        int selectedItem = getSelecledCompare(info.mCompare);

        new AlertDialog.Builder(getContext())
        .setTitle(R.string.selectcompare)
        .setSingleChoiceItems(mBijinpingArray, selectedItem,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int which) {
                        if(which == 0){
                            button.setText("");
                        }else{
                            button.setText(mBijinpingArray[which]);
                        }
                        dialog.dismiss();
                        info.mCompare = mBijinpingValueArray[which];
                    }
                }).show();
    }

    /**
     * 选择层对话框
     * @param button 层View
     */
    private void popSeleteFloorDialog(final Button button){
        int selectedItem = -1;
        if(mGoodsFloor == INVALID_VALUE){
        	selectedItem = -1;
        }else{
        	selectedItem = mGoodsFloor;
        }
        new AlertDialog.Builder(getContext())
        .setTitle(R.string.selectfloor)
        .setSingleChoiceItems(mFloorType, selectedItem,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int which) {
                    	mGoodsFloor = which;
                    	button.setText(getFloorText(which));
                    	dialog.dismiss();
                    }
                }).show();
    }

    /**
     * 选择货仓对话框
     * @param button 货仓View
     */
    private void popSeleteTypeDialog(final Button button){
        int selectedItem = -1;
        if(mGoodsType == INVALID_VALUE){
            selectedItem = -1;
        }else{
            selectedItem = mGoodsType;
        }
        new AlertDialog.Builder(getContext())
        .setTitle(R.string.selecttype)
        .setSingleChoiceItems(mStoreType, selectedItem,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int which) {
                        mGoodsType = which;
                        button.setText(getTypeText(which));
                        dialog.dismiss();
                    }
                }).show();
    }

    private int getSelecledTechen(String value){
        if(value == null || value.trim().length() == 0 || value.equals(DEFAULT)){
            return 0;
        }else{
            for(int i = 0; i < mTechenValueArray.length; i++){
                if(mTechenValueArray[i].equals(value)){
                    return i;
                }
            }
        }
        return 0;
    }

    private int getSelecledCompare(String value){
        if(value == null || value.trim().length() == 0 || value.equals(DEFAULT)){
            return 0;
        }else{
            for(int i = 0; i < mBijinpingValueArray.length; i++){
                if(mBijinpingValueArray[i].equals(value)){
                    return i;
                }
            }
        }
        return 0;
    }

    private String getSelectCompareString(String value){
        int sid = getSelecledCompare(value);
        String techen = "";
        if(sid > 0){
            techen = mBijinpingArray[sid];
        }
        return techen;
    }

    private String getSelectString(String value){
        int sid = getSelecledTechen(value);
        String techen = "";
        if(sid > 0){
            techen = mTechenArray[sid];
        }
        return techen;
    }

    /**
     * 歇业门店对话框
     */
    private void popDeleteDialog() {
        Actions.alertShowDetails(getContext(), getContext().getString(R.string.stopbusinessclew),
                getContext().getString(R.string.stopbusinesscontent),
                R.string.queding, R.string.cancel,
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {
                    	boolean success = Util.saveStoresClose(ProductInfoListView.this.getContext(), mVisitTaskInfo.mDbId);
                    	if(success){
                    		mProductInfoListActivity.setResult(StoreEvaluationActivity.RESULT_OK);
                    		mProductInfoListActivity.finish();
                    	}
                    }
                }, new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {

                    }
                });
    }

    /**
     * 获取提醒消息
     * @param cid 门店ID
     */
    private String getRemindText(String cid){
        String remindtext = null;
        Cursor cursor = null;
        try{
            String where = SalesSettings.RemindsColumns.CUSTOMERID + " = \'" + cid +"\'";
            cursor = getContext().getContentResolver().query(SalesSettings.RemindsColumns.CONTENT_URI_NO_NOTIFICATION, null, where, null, null);
            while (cursor.moveToNext()) {
                String text = cursor.getString(cursor.getColumnIndexOrThrow(SalesSettings.RemindsColumns.TEXT));
                if(text != null && text.length() > 0){
                    remindtext = text;
                    break;
                }
            }
        }catch(Exception e){
            e.printStackTrace();
            remindtext = null;
        }finally{
            if(cursor != null){
                cursor.close();
                cursor = null;
            }
        }
//        if(remindtext == null){
//            remindtext = this.getContext().getString(R.string.noremind);
//        }
        return remindtext;
    }

    /**
     * 弹出提醒对话框
     * @param content 上下文
     */
    private void popRemindDialog(String content){
		if (content == null || content.trim().length() == 0) {
			return;
		}
		if (mRemindView == null) {
			mRemindView = mProductInfoListActivity.getLayoutInflater().inflate(
					R.layout.layout_popdialog, null);
			mRemindView.setOnClickListener(this);
			ImageView close = (ImageView) mRemindView
					.findViewById(R.id.checkpop_close);
			close.setOnClickListener(this);
		}
		TextView name = (TextView) mRemindView
				.findViewById(R.id.checkpop_title);
		name.setText(this.getContext().getString(R.string.remindtitle));
		TextView text = (TextView) mRemindView.findViewById(R.id.checkpop_Text);
		text.setText(content);
		this.addView(mRemindView);
    }

    /**
     * 移除提醒框
     */
    private void removeRemind(){
    	if (mRemindView != null && this.indexOfChild(mRemindView) != -1) {
            this.removeView(mRemindView);
        }
    }

    /**
     * 处理返回
     */
    public boolean doBack(){
        if(this.indexOfChild(mRemindView) != -1){
        	this.removeView(mRemindView);
            return true;
        }
        return false;
    }

    private final TextWatcher mTextSideEditorWatcher = new TextWatcher() {

        private int mStart = 0;
        private int mCount = 0;

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            mStart = start;
            mCount = count;
        }

        public void afterTextChanged(Editable s) {
            int maxCount = 0;
            String side = mSideText.getText().toString().trim();
            if(side != null && side.length() > 0){
                maxCount = Integer.parseInt(side);
            }
            if(s != null && s.toString().length() > 0){
                int cur = Integer.parseInt(s.toString());
                if(cur > maxCount){
                    s.delete(mStart, mStart + mCount);
                    //Actions.toastShort(ProductInfoListView.this.getContext(), ProductInfoListView.this.getContext().getString(R.string.floorerror));
                }
            }
        }
    };

    private final TextWatcher mTextSideInfoEditorWatcher = new TextWatcher() {
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        public void afterTextChanged(Editable s) {
//            if(hasErrorData()){
//                popChangeSideDialog();
//            }
            doChangeSide();
        }
    };

    private final TextWatcher mTextFloorInfoEditorWatcher = new TextWatcher() {
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        public void afterTextChanged(Editable s) {
            doChangeFloor();
        }
    };

    /**
     * 切换面
     */
    private void doChangeSide(){
        ProductInfo temInfo = null;
        View view = null;
        int maxSide = 0;
        String maxSideStr = mSideText.getText().toString();
        if (maxSideStr == null || maxSideStr.trim().length() < 1) {
            maxSide = 0;
        }else{
            maxSide = Integer.parseInt(maxSideStr);
        }
        for (int i = 0; i < mBodyView.getChildCount(); i++) {
            view = mBodyView.getChildAt(i);
            temInfo = (ProductInfo) view.getTag();
            if (temInfo.id == null) {
                continue;
            }
            EditText textView3 = (EditText) view.findViewById(R.id.text3);
            String sideStr = textView3.getText().toString().trim();
            if(sideStr != null && sideStr.trim().length() > 0){
                int side = Integer.parseInt(sideStr);
                if(side > maxSide){
                    textView3.setText("");
                }
            }
        }
    }

    private void doChangeFloor(){
        ProductInfo temInfo = null;
        View view = null;
        int maxSide = 0;
        String maxSideStr = getFloorValue(mGoodsFloor);//mFloorText.getText().toString();
        if (maxSideStr == null || maxSideStr.trim().length() < 1) {
            maxSide = 0;
        }else{
            maxSide = Integer.parseInt(maxSideStr);
        }
        for (int i = 0; i < mBodyView.getChildCount(); i++) {
            view = mBodyView.getChildAt(i);
            temInfo = (ProductInfo) view.getTag();
            if (temInfo.id == null) {
                continue;
            }
            Button textView3 = (Button) view.findViewById(R.id.text2);
            String sideStr = textView3.getText().toString().trim();
            if(sideStr != null && sideStr.trim().length() > 0){
                int side = Integer.parseInt(sideStr);
                if(side > maxSide){
                    textView3.setText("");
                }
            }
        }
    }

    private boolean hasErrorData(){
        ProductInfo temInfo = null;
        View view = null;
        int maxSide = 0;
        String maxSideStr = mSideText.getText().toString();
        if (maxSideStr == null || maxSideStr.trim().length() < 1) {
            maxSide = 0;
        }else{
            maxSide = Integer.parseInt(maxSideStr);
        }
        for (int i = 0; i < mBodyView.getChildCount(); i++) {
            view = mBodyView.getChildAt(i);
            temInfo = (ProductInfo) view.getTag();
            if (temInfo.id == null) {
                continue;
            }
            EditText textView3 = (EditText) view.findViewById(R.id.text3);
            String sideStr = textView3.getText().toString().trim();
            if(sideStr != null && sideStr.trim().length() > 0){
                int side = Integer.parseInt(sideStr);
                if(side > maxSide){
                    return true;
                }
            }
        }
        return false;
    }

    private void popChangeSideDialog(){
        Actions.alertShowDetails(this.getContext(), this.getContext().getString(R.string.floorchange),
                this.getContext().getString(R.string.floorchangecontent),
                R.string.queding, R.string.cancel,
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {
                        doChangeSide();
                    }
                }, new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {

                    }
                });
    }

    private String getFloorText(int selectIndex){
//    	if(selectIndex >= 0 && selectIndex < mFloorType.length){
//    		return mFloorType[selectIndex];
//    	}
    	return "" + selectIndex;
    }

    private String getFloorValue(int selectIndex){
    	if(selectIndex >= 0 && selectIndex < mFloorValue.length){
    		return mFloorValue[selectIndex];
    	}
    	return "0";
    }

    private String getTypeText(int selectIndex){
        if(selectIndex >= 0 && selectIndex < mStoreType.length){
            return mStoreType[selectIndex];
        }
        return "";
    }

    public boolean checkInputData(){
        if(mGoodsFloor == INVALID_VALUE || mGoodsSide == INVALID_VALUE || mGoodsPlace == INVALID_VALUE){
            return false;
        }
        return true;
    }
}
